//
//  HMComposeViewController.swift
//  HMVVeibo23
//
//  Created by apple on 17/2/8.
//  Copyright © 2017年 apple. All rights reserved.
//

import UIKit

class HMComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setNavUI()
        setupUI()
    }
    
    private func setNavUI()-> Void {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: nil, title: "取消", target: self, action: #selector(cancelItemClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: nil, title: "发送", target: self, action: #selector(sendClick))
        
        navigationItem.rightBarButtonItem?.isEnabled = false
        navigationItem.titleView = titleVieww
        
    }
    
    ///'取消'按钮点击事件
    func cancelItemClick()-> Void {
    
        self.dismiss(animated: true, completion: nil)
        self.textView.resignFirstResponder()
    }
    /// '发送按钮'点击事件
    func sendClick() -> Void {
        
        if self.pictureView.imageArr.count > 0 {
            
            issuanceMicroblogText()
        } else {
        
//            print("没有配图")
            issuanceMicroblogPicture()
            
        }
        
    }
    
    //MARK: - 设置视图
    private func setupUI(){
        view.backgroundColor = randomeColor()
        
        /// 添加文本视图
        view.addSubview(textView)
        textView.delegate = self
        textView.closure = {[weak self](isEnabled)->() in
        
            self?.navigationItem.rightBarButtonItem?.isEnabled = isEnabled
        }
        // 在文本视图中添加图片view
        textView.addSubview(pictureView)
        pictureView.closure = {[weak self] ()->() in
        
            //调出相册
            self?.selectImage()
        }
        

        /// 添加底部视图
        view.addSubview(bottomView)
        
        
        textView.snp_makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        
        pictureView.snp_makeConstraints { (make) in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.size.equalTo(CGSize(width: SCREENWIDTH - 20, height: SCREENWIDTH - 20))
        }
        bottomView.snp_makeConstraints { (make) in
            make.bottom.right.left.equalTo(view)
            make.height.equalTo(40)
        }
        
        //使用通知监听键盘
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
       
        
        
        
        bottomView.closure = {[weak self] (type)->() in
        
            switch type {
            case .picture:
//                print("图片")
                self?.selectImage()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("笑脸")
                self?.smilingBtnClick()
            case .add:
                print("+")
            
            }
        }
        
    }
    
    
    // 导航栏标题
    private lazy var titleVieww:UILabel = {
    
        let name = HMOAuthModel.shared.userAccountModel?.screen_name ?? ""
        let str = "发微博\n\(name)"

//        // 获取范围 -> OC
        let range = (str as NSString).range(of: name)
        // 可变富文本
        let attr = NSMutableAttributedString(string: str)
        // 设置富文本的属性 字体的颜色和字体的大小
        attr.addAttributes([NSForegroundColorAttributeName: themeColor, NSFontAttributeName: UIFont.systemFont(ofSize: 12)], range: range)
        
        
        let lab = UILabel()
        // 设置text
        lab.attributedText = attr
        // 换行
        lab.numberOfLines = 0
        // 对齐方式
        lab.textAlignment = .center
        // 设置大小
        lab.sizeToFit()
        
        return lab
        
    }()
    
    // 文本视图
    fileprivate lazy var textView: HMComposeTextView = {
    
        let textV = HMComposeTextView()
        textV.font = UIFont.systemFont(ofSize: midTextFont)
        textV.delegate = self
        //允许垂直滚动
        textV.alwaysBounceVertical = true
        return textV
    }()
    
    // 底部视图
    fileprivate lazy var bottomView: HMComposeBottomVIew = HMComposeBottomVIew()
    
    // 图片视图
    fileprivate lazy var pictureView: HMComposePictureView = {
    
        let picv = HMComposePictureView()
        return picv
    }()
    
    // MARK: 表情键盘
    fileprivate lazy var expressionKeyBoard:HMExpressionKeyBoard = HMExpressionKeyBoard()
    
    // touchesBegan
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        dismiss(animated: true, completion: nil)
    }
    
}

// MARK: 键盘监听方法
extension HMComposeViewController {

    //让底部视图跟随键盘一起移动
    func keyboardWillChangeFrame(noti:NSNotification) -> Void {
        
        guard let userInfo = noti.userInfo as? [String:Any] else {
            return
        }
        
//        print(userInfo) //键盘移动时间
        let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        // 监听到的键盘frame
        let keyBoardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        // 刷新
         self.bottomView.snp_updateConstraints { (make) in
            make.bottom.equalTo(keyBoardFrame.origin.y - SCREENHEIGHT)
        }
        // 底部view动画
        UIView.animate(withDuration: duration) {
            
            self.view.layoutIfNeeded()
        }
    }
}

// 监听底部视图按钮点击事件
extension HMComposeViewController {

    // 图片按钮
    func selectImage () -> Void {
        
        //实例化 跳转到相册
        let picker = UIImagePickerController()
        //
        picker.delegate = self
        
        self.present(picker, animated: true, completion: nil)
    }
    
    // 笑脸按钮
    func smilingBtnClick() -> Void {
        
        
        //判断键盘是否为系统的键盘 如果是就设置自定义键盘
        if self.textView.inputView == nil {
            //如果为nil就是系统的键盘 切换为自定义键盘
            self.textView.inputView = self.expressionKeyBoard
            //还要切换图片
            self.bottomView.isEmoticon = true
            
        } else {
        
            //如果不为nil就是自定义键盘 切换为系统键盘
            self.textView.inputView = nil
            self.bottomView.isEmoticon = false
        }
        // 设置第一响应者
        
        self.textView.becomeFirstResponder()
        self.textView.reloadInputViews()
    }
    
}

extension HMComposeViewController:UITextViewDelegate {

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        self.textView.resignFirstResponder()
    }
}


///pickerController代理方法
extension HMComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    // 获取额内容
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//        print(info)
        // 拿到从相册里点击的image
//        let image = info[UIImagePickerControllerReferenceURL] as! UIImage
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let img = dealImageScale(image: image, width: 400)
        // 用图形上下文处理一下然后返回给pictureView
        self.pictureView.addImage(img: img)
        picker.dismiss(animated: true, completion: nil)
    }
    
    func dealImageScale(image:UIImage, width:CGFloat) -> UIImage {
        
        //如果小于指定的宽度就返回
        if image.size.width < width {
            return image
        }
        
        //根据比例计算高度
        let h = width * image.size.height / image.size.width
        let size = CGSize(width: width, height: h)
        
        // 开启图形上下文
        UIGraphicsBeginImageContext(size)
        // 把图片渲染到上下文
        image.draw(in: CGRect(x: 0, y: 0, width: width, height: h))
        // 从图形上下文获取图片
        let img = UIGraphicsGetImageFromCurrentImageContext()!
        // 关闭图形上下文
        UIGraphicsEndImageContext()
        
        return img
    }
}

extension HMComposeViewController {

    // MARK: 发布文字微博
    func issuanceMicroblogText() -> Void {
        NetworkTools.sharedNetworkTools.sendSinaMicroblogPicture(microblogText: self.textView.text, images: self.pictureView.imageArr, success: { (_) in
            print("上传图片微博成功")
            self.dismiss(animated: true, completion: nil)
        }, failure: { (error) in
            print("上传图片微博失败")
        })
    }
    // MARK: 发布文字图片微博
    func issuanceMicroblogPicture() -> Void {
        
        NetworkTools.sharedNetworkTools.sendSinaMicroblog(microblogText: self.textView.text, isFinish: { (isSendOk) in
            
            if isSendOk {
                
                print("微博发送ok")
                self.dismiss(animated: true, completion: nil)
            } else {
                print("微博发送failure")
            }
            
            
        })
        
    }

}
